package com.huonan.utils;

import java.io.*;

/**
 * 流水读取并写入文件，指定写入文件的批大小
 */
public class FileReadWriteExample {
    public static void main(String[] args) {
        String inPath = "/Users/lxp/IdeaProjects/Study/MainTest/data/inData/1.json";
        String outPath = "/Users/lxp/IdeaProjects/Study/MainTest/data/inData/11.json";
        int batchSize = 2; // 每次读取的行数
        int linesRead = 0; // 计数器
        try (BufferedReader reader = new BufferedReader(new FileReader(inPath));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outPath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                // 对读取的每一行进行处理
                String processedLine = processLine(line);
                // 将处理后的行写入新文件
                writer.write(processedLine);
                writer.newLine(); // 写入换行符
                linesRead++;
                if (linesRead >= batchSize) {
                    // 达到指定的行数，将缓冲区内容写入文件并清空缓冲区
                    writer.flush();
                    linesRead = 0;
                }
            }
            // 将剩余的缓冲区内容写入文件
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String processLine(String line) {
        // 对读取的每一行进行处理
        return line.toUpperCase();
    }
}
